##Chapte87Master.r
###master script for creating all Tables and Figures 
###in original analysis included in Chapter 8 of:
###Enos, Ryan D. 2017. The Space Between Us:
### Social Geography and Politics
####RdE May 2018

rm(list=ls())

library(spdep)
library(xtable)
library(Zelig)
library(apsrtable)
library(ggplot2)
library(car)
library(lmtest)



##clustered standard errors function
##this is slightly different than in other code for the book because the required output is different
cl <- function(dat,fm, cluster,Xs) {
  attach(dat, warn.conflicts = F)
  library(sandwich)
  M <- length(unique(cluster))   
  N <- length(cluster)              
  K <- fm$rank                   
  dfc <- (M/(M-1))*((N-1)/(N-K))  
  uj  <- apply(estfun(fm),2, function(x) tapply(x, cluster, sum));
  vj = uj[is.na(uj[,1])==F,]
  vcovCL <- dfc*sandwich(fm, meat=crossprod(vj)/N)
  vjs = crossprod(vj)
  coefs = coeftest(fm, vcovCL)
  output = list()
  output$coefficients = coefs
  output$vcov <- vcovCL
  return(output)   
  }




source('TablesA31A32Figure8_6.r')
source('TableA33.r')